package com.mall.controller;

import com.mall.common.Result;
import com.mall.entity.Message;
import com.mall.mapper.MessageMapper;
import com.mall.mapper.UserMapper;
import com.mall.util.JwtUtil;
import com.mall.websocket.ChatWebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 聊天控制器
 * 
 * @author mall
 * @since 2024-01-01
 */
@RestController
@RequestMapping("/chat")
@CrossOrigin
public class ChatController {

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private ChatWebSocketHandler chatWebSocketHandler;

    /**
     * 获取聊天历史记录
     */
    @GetMapping("/history")
    public Result<List<Message>> getChatHistory(
            @RequestHeader("Authorization") String token,
            @RequestParam(required = false) Long receiverId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer size) {
        
        try {
            String jwtToken = token.substring(7);
            Long userId = jwtUtil.getUserIdFromToken(jwtToken);
            
            // 构建查询条件
            com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Message> queryWrapper = 
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
            
            // 查询与指定用户的聊天记录，或者查询所有消息（如果是客服）
            if (receiverId != null) {
                queryWrapper.and(wrapper -> wrapper
                    .eq("sender_id", userId).eq("receiver_id", receiverId)
                    .or()
                    .eq("sender_id", receiverId).eq("receiver_id", userId)
                );
            } else {
                // 客服可以查看所有消息
                queryWrapper.or(wrapper -> wrapper
                    .eq("sender_id", userId)
                    .or()
                    .eq("receiver_id", userId)
                );
            }
            
            queryWrapper.orderByDesc("create_time")
                       .last("LIMIT " + (page - 1) * size + ", " + size);
            
            List<Message> messages = messageMapper.selectList(queryWrapper);
            
            return Result.success(messages);
        } catch (Exception e) {
            return Result.error("获取聊天记录失败");
        }
    }

    /**
     * 发送消息
     */
    @PostMapping("/send")
    public Result<String> sendMessage(
            @RequestHeader("Authorization") String token,
            @RequestBody Map<String, Object> messageRequest) {
        
        try {
            String jwtToken = token.substring(7);
            Long senderId = jwtUtil.getUserIdFromToken(jwtToken);
            
            String messageType = (String) messageRequest.get("messageType");
            String content = (String) messageRequest.get("content");
            Long receiverId = messageRequest.get("receiverId") != null ? 
                Long.valueOf(messageRequest.get("receiverId").toString()) : null;
            String commandType = (String) messageRequest.get("commandType");
            String commandParams = (String) messageRequest.get("commandParams");
            
            // 创建消息
            Message message = new Message();
            message.setSenderId(senderId);
            message.setReceiverId(receiverId);
            message.setMessageType(messageType);
            message.setContent(content);
            message.setStatus(0);
            message.setIsBroadcast(receiverId == null ? 1 : 0);
            message.setCommandType(commandType);
            message.setCommandParams(commandParams);
            message.setCreateTime(LocalDateTime.now());
            
            // 保存消息
            messageMapper.insert(message);
            
            return Result.success("消息发送成功");
        } catch (Exception e) {
            return Result.error("消息发送失败");
        }
    }

    /**
     * 获取在线用户列表
     */
    @GetMapping("/online-users")
    public Result<Map<String, Object>> getOnlineUsers(@RequestHeader("Authorization") String token) {
        try {
            String jwtToken = token.substring(7);
            Long userId = jwtUtil.getUserIdFromToken(jwtToken);
            
            Map<String, Object> result = new java.util.HashMap<>();
            result.put("onlineCount", chatWebSocketHandler.getOnlineUserCount());
            result.put("onlineUsers", chatWebSocketHandler.getOnlineUsers().keySet());
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取在线用户失败");
        }
    }

    /**
     * 标记消息为已读
     */
    @PutMapping("/read/{messageId}")
    public Result<String> markAsRead(
            @RequestHeader("Authorization") String token,
            @PathVariable Long messageId) {
        
        try {
            String jwtToken = token.substring(7);
            Long userId = jwtUtil.getUserIdFromToken(jwtToken);
            
            Message message = messageMapper.selectById(messageId);
            if (message != null && message.getReceiverId().equals(userId)) {
                message.setStatus(1); // 已读
                message.setUpdateTime(LocalDateTime.now());
                messageMapper.updateById(message);
                
                return Result.success("消息已标记为已读");
            } else {
                return Result.error("消息不存在或无权限");
            }
        } catch (Exception e) {
            return Result.error("标记消息失败");
        }
    }

    /**
     * 客服推送消息给用户
     */
    @PostMapping("/push")
    public Result<String> pushMessage(
            @RequestHeader("Authorization") String token,
            @RequestBody Map<String, Object> pushRequest) {
        
        try {
            String jwtToken = token.substring(7);
            Long senderId = jwtUtil.getUserIdFromToken(jwtToken);
            
            // 验证是否为客服或管理员
            com.mall.entity.User user = userMapper.selectById(senderId);
            if (user.getUserType() < 2) {
                return Result.error("无权限推送消息");
            }
            
            Long receiverId = Long.valueOf(pushRequest.get("receiverId").toString());
            String messageType = (String) pushRequest.get("messageType");
            String content = (String) pushRequest.get("content");
            String commandType = (String) pushRequest.get("commandType");
            String commandParams = (String) pushRequest.get("commandParams");
            
            // 创建推送消息
            Message message = new Message();
            message.setSenderId(senderId);
            message.setReceiverId(receiverId);
            message.setMessageType(messageType);
            message.setContent(content);
            message.setStatus(0);
            message.setIsBroadcast(0);
            message.setCommandType(commandType);
            message.setCommandParams(commandParams);
            message.setCreateTime(LocalDateTime.now());
            
            // 保存消息
            messageMapper.insert(message);
            
            // 通过WebSocket推送消息
            chatWebSocketHandler.sendMessageToUser(receiverId, 
                createPushMessage(message));
            
            return Result.success("消息推送成功");
        } catch (Exception e) {
            return Result.error("消息推送失败");
        }
    }

    /**
     * 创建推送消息
     */
    private String createPushMessage(Message message) {
        try {
            Map<String, Object> messageData = new java.util.HashMap<>();
            messageData.put("type", "push");
            messageData.put("messageId", message.getId());
            messageData.put("senderId", message.getSenderId());
            messageData.put("messageType", message.getMessageType());
            messageData.put("content", message.getContent());
            messageData.put("createTime", message.getCreateTime());
            messageData.put("commandType", message.getCommandType());
            messageData.put("commandParams", message.getCommandParams());
            
            com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
            return mapper.writeValueAsString(messageData);
        } catch (Exception e) {
            return "{}";
        }
    }
}
